package com.ease.common.exception;

/**
 * converts any checked exception into a RuntimeException while preserving all the information from the checked exception.
 */

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 
 * @author nathanleewei
 * 
 */
public class WrapperException extends RuntimeException {

	/**
	 *
	 */
	private static final long serialVersionUID = 8700285002355073917L;

	private final String stackTrace;

	public Exception originalException;

	public static String getStackTrace(Exception e) {
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		return sw.toString();
	}

	public WrapperException(Exception e) {
		super(e.toString());
		originalException = e;
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		stackTrace = sw.toString();
	}

	public WrapperException(Exception e, String msg) {
		super(msg + " detailed: " + e.toString());
		originalException = e;
		StringWriter sw = new StringWriter();
		e.printStackTrace(new PrintWriter(sw));
		stackTrace = sw.toString();
	}

	public WrapperException(String msg, Exception e) {
		this(e, msg);
	}

	public void printStackTrace() {
		printStackTrace(System.err);
	}

	public void printStackTrace(java.io.PrintStream s) {
		synchronized (s) {
			s.print(getClass().getName() + ": ");
			s.print(stackTrace);
		}
	}

	public void printStackTrace(java.io.PrintWriter s) {
		synchronized (s) {
			s.print(getClass().getName() + ": ");
			s.print(stackTrace);
		}
	}

	public void reThrow() throws Exception {
		throw originalException;
	}
}
